package com.homegoods.orderinfodetail.ui.activity;

import android.annotation.SuppressLint;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.homegoods.area.AreaEvent;
import com.homegoods.orderinfodetail.R;
import com.homegoods.orderinfodetail.bean.AddressBean;
import com.homegoods.orderinfodetail.databinding.InfoActivityAddNewAddressBinding;
import com.homegoods.orderinfodetail.model.AddressModel;
import com.homegoods.orderinfodetail.presenter.AddNewAddressPresenter;
import com.homegoods.orderinfodetail.ui.AreaPickerView;
import com.homegoods.orderinfodetail.ui.view.IAddAddressView;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.util.RxBus;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;


/**
 * 编辑地址
 *
 * @author QiQi
 */
@Route(path = ARouterPath.PATH_ADD_NEW_ADDRESS)
public class AddNewAddressActivity extends MyBaseFragmentActivity<InfoActivityAddNewAddressBinding, AddNewAddressPresenter> implements IAddAddressView {

    /**
     * 从我的收货地址界面传来的数据，当有编辑地址的情况下
     */
    @Autowired(name = "data")
    public AddressModel addressModel;

    /**
     * 从我的收货地址界面传来的数据，当有编辑地址的情况下，指明当前地址数据在列表中所处的位置
     */
    @Autowired
    public int index;

    //add shibo.zheng start
    private AreaPickerView areaPickerView;  //选择地区三方控件
    private List<AddressBean> addressBeans; //保存地区的list
    private int[] i;
    //add shibo.zheng endcompile


    @Override
    public int getLayout() {
        return R.layout.info_activity_add_new_address;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initEvent() {
        if (addressModel != null) {
            mPresenter.setAddressModel(index, addressModel);
            setTitle("编辑地址");
        } else {
            addressModel = new AddressModel();
        addressCall();  //add shibo.zheng
        }
        //接收区域选择结果
        RxBus.getDefault().toFlowable(AreaEvent.class)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(areaEvent -> {
                    Log.d(TAG, "accept: zheliyinggaibuhuizouba");
                    mPresenter.area.set(/*areaEvent.getAreaName()*/addressModel.getAreaNameTree());
                    mPresenter.setPostAreaSid(/*areaEvent.getSid()*/addressModel.getSid());
                });
//        RxBus.getDefault().toFlowable(AreaEvent.class)
//                .compose(bindToLifecycle())
//                .map(areaEvent -> areaEvent.getAreaModels())
//                .flatMap(Flowable::fromIterable)
//                .reduce("", (s, areaModel) -> s.concat(areaModel.getAreaName()))
//                .subscribe(area -> mPresenter.area.set(area));
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        ARouter.getInstance().inject(this);
        mBinding.setItem(mPresenter);
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        setTitle("添加新地址");
    }

    @Override
    protected AddNewAddressPresenter getPresenter() {
        return new AddNewAddressPresenter(this);
    }

    //所在地区选择
    public void onSelectedAreaClick(View view) {
        //modify shibo.zheng start
        /*ARouter.getInstance()
                .build(ARouterPath.PATH_AREA)
                .navigation();*/
        areaPickerView.setSelect(i);
        areaPickerView.show();
        //modify shibo.zheng end
    }

    //add shibo.zheng start
    //通过本地json文件，获取地区
    private String getCityJson() {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = this.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open("region.json")));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    //通过选择地区回调获取到所选择的地区名称及地区id
    private void addressCall() {
        addressBeans = JSON.parseObject(getCityJson(), new TypeReference<ArrayList<AddressBean>>() {
        });

        areaPickerView = new AreaPickerView(this, R.style.InfoDialog, this.addressBeans);
        areaPickerView.setAreaPickerViewCallback(value -> {
            i=value;
            String addressNameTree; //地区名称如：上海上海市浦东新区
            String areaSid; //返回的地区id
            if (value.length == 3) {
                addressNameTree = addressBeans.get(value[0]).getLabel() + addressBeans.get(value[0]).getChildren().get(value[1]).getLabel() + addressBeans.get(value[0]).getChildren().get(value[1]).getChildren().get(value[2]).getLabel();
                areaSid = addressBeans.get(value[0]).getChildren().get(value[1]).getChildren().get(value[2]).getValue();
                mBinding.areaName.setText(addressNameTree);
                Log.d(TAG, "addressCall: addressBeans id == " + areaSid);
            } else {
                addressNameTree = addressBeans.get(value[0]).getLabel() + addressBeans.get(value[0]).getChildren().get(value[1]).getLabel();
                areaSid = addressBeans.get(value[0]).getChildren().get(value[1]).getValue();
                mBinding.areaName.setText(addressNameTree);
                Log.d(TAG, "addressCall: != 3 bean id  == " + areaSid);
            }
            addressModel.setAreaNameTree(addressNameTree);
            addressModel.setAreaSid(areaSid);
            mPresenter.setPostAreaSid(/*areaEvent.getSid()*/addressModel.getAreaSid());
        });
    }
    //add shibo.zheng end

    @Override
    public boolean isCheck() {
        return mBinding.svCheck.isCheck();
    }

    @Override
    public void submit() {
        finish();
    }
}
